package com.le.tester.webpage.redis.controller;

import com.le.tester.common.ServerResponse;
import com.le.tester.common.enums.ResponseCode;
import com.le.tester.utils.RedisUtil;
import com.le.tester.webpage.redis.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：使用redis进行简单的缓存
 */
@Controller
@RequestMapping("/")
public class RedisCacheController {
    private static final Logger LOG = LoggerFactory.getLogger(RedisCacheController.class);

    @Autowired
    private RedisService redisService;

    @Resource
    private RedisUtil redisUtil;

    @ResponseBody
    @RequestMapping("hello")
    public String hello(@RequestParam int name) {
        LOG.info("没有走缓存");
        System.out.println(redisUtil.get("test_key"));

        return "Hello " + name;
    }

    /**
     * 发送手机短信验证码，使用redis来存储手机短信验证码
     *
     * @param mobile
     * @return
     */
    @ResponseBody
    @RequestMapping("sendSM")
    public ServerResponse<String> sendSms(@RequestParam("mobile") String mobile) {
        //手机号码验证
        boolean isPhoneCode = redisService.checkedPhoneCode(mobile);
        if (!isPhoneCode) {
            return ServerResponse.createByErrorCodeMessage(
                    ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        try {
            //发送手机验证码
            redisService.sendAuthCode(mobile);
            return ServerResponse.createBySuccessCodeMessage(ResponseCode.SMS_SUCCESS.getCode(), ResponseCode.SMS_SUCCESS.getDesc());
        } catch (Exception ex) {
            LOG.warn("发送手机验证码失败，手机号码:{},异常信息:{}", mobile, ex.getMessage());
            return ServerResponse.createByErrorCodeMessage(Integer.parseInt(ex.getMessage()), ResponseCode.SMS_ERROR.getDesc());
        }
    }


}
